const path = require("path");
const fs = require("fs");
const prompts = require("prompts");

function getArg(name, defaultValue = '') {
  const index = process.argv.indexOf(name);
  return index > 0 ? process.argv[index + 1] : defaultValue;
}

function hasArg(name) {
  return process.argv.indexOf(name) > 0;
}

function hasArgs(names = []) {
  for (const name of names) {
    if (process.argv.indexOf(name) > 0) {
      return true;
    }
  }
  return false;
}

async function resetPagesJsonPath() {
  const R = process.cwd();
  const projectsDir = path.join(R, 'src/projects');

  if (!fs.existsSync(projectsDir)) {
    process.env.PROJECT_PAGES_JSON = path.join(R, 'src/pages.json');
    return;
  }

  let project = getArg('--project');
  let env = getArg('--env');
  // const isMp = hasArgs(['mp-alipay', 'mp-baidu', 'mp-jd', 'mp-kuaishou', 'mp-lark', 'mp-qq', 'mp-toutiao', 'mp-weixin']);
  const isH5 = !hasArg('-p') || hasArg('h5')

  if (!project) {
    const projects = fs.readdirSync(projectsDir);

    const resp = await prompts([
      {
        type: 'select',
        name: 'project',
        message: '请选择您要启动的项目',
        choices: projects.map(name => {
          return {
            title: name,
            value: name,
          }
        }),
      },
    ]);

    project = resp.project;
  }

  // 仅H5平台支持运行环境
  if (!env && isH5) {
    const resp = await prompts([
      {
        type: 'select',
        name: 'env',
        message: '请选择运行环境',
        choices: [
          {
            title: '开发环境',
            value: 'develop',
          },
          {
            title: '体验环境',
            value: 'trial',
          },
          {
            title: '正式环境',
            value: 'release',
          }
        ],
      },
    ]);

    env = resp.env;
  }

  process.env.CURRENT_ENV = env || '';
  process.env.CURRENT_PROJECT = project;

  process.env.PROJECT_ROOT_DIR = path.join(R, 'src/projects', project);
  process.env.PROJECT_PAGES_JSON = path.join(R, 'src/projects', project, 'pages.json');
  process.env.PROJECT_PAGES_JS = path.join(R, 'src/projects', project, 'pages-json-js');
  process.env.PAGES_JSON_JS = ['projects', project, 'pages-json-js'].join('/');

  process.env.PROJECT_MANIFEST_JSON = path.join(R, 'src/projects', project, 'manifest.json');
  process.env.PROJECT_MANIFEST_JS = path.join(R, 'src/projects', project, 'manifest-json-js');
  process.env.MANIFEST_JSON_JS = ['projects', project, 'manifest-json-js'].join('/');
}

exports.resetPagesJsonPath = resetPagesJsonPath